<?php

namespace catchAdmin\registration\controller;

use catcher\Utils;
use catcher\CatchResponse;
use catcher\base\CatchRequest;
use catcher\base\CatchController;
use catcher\library\excel\Excel;
use catcher\exceptions\FailedException;
use catchAdmin\registration\service\TaskService;
use app\common\model\PatientInfo as PatientInfoModel;
use catchAdmin\registration\service\StatisticsService;
use catchAdmin\archives\excel\LostExport;

class LostFollow extends CatchController
{
    /**
     * 失访患者列表
     * @time 2024年01月08日
     * @return \think\response\Json
     */
    public function index(): \think\response\Json
    {
        $where[] = ['lost_access', '=', 1];
        $field = 'id,name,medicalRecordsNo,sex,nation,presentTelphone,bz,inList,follow_node,lost_access_result,lost_access_date,patientId';
        $ret = (new PatientInfoModel())->getSearchConditionData($where, $field, 'lost_access_date');

        foreach ($ret as $k => $v) {
            $bingzhong_string = '';
            if (isset($v['bz']['bingzhongArr'])) {
                $bingzhong_array = array_column($v['bz']['bingzhongArr'], 'bingzhong_name');
                $bingzhong_string = implode(',', $bingzhong_array);
            }
            $ret[$k]['bz'] = $bingzhong_string;
        }
        return CatchResponse::paginate($ret);
    }

    /**
     * 撤销失访患者
     * @time 2024年01月08日
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function revokeLostPatient(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        if (!isset($req['id']) || empty($req['id'])) {
            throw new FailedException('id参数不能为空');
        }

        if (!is_array($req['id'])) {
            throw new FailedException('id参数必须为数组类型');
        }
        $ret = (new TaskService())->batchRevocationLost($req['id']);
        return CatchResponse::success($ret);
    }

    /**
     * 失访统计图
     * @time 2024年01月08日
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function chartLostStatistics(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success((new StatisticsService())->LostStatisticsChart());
    }

    /**
     * 失访导出
     * @time 2024年01月30日
     * @return \think\response\Json
     */
    public function exports(Excel $excel, LostExport $followExport)
    {
        set_time_limit(0);
        ini_set("memory_limit","2G");
        return CatchResponse::success($excel->save($followExport, Utils::publicPath('export/lost')));
    }
}